import urllib
import urllib2


class Plurk:
    def __init__(self, username, password, api_key):
        self.username = username
        self.password = password
        self.api_key = api_key
        self.plurk_url = "http://www.plurk.com/API"
        return

    def plurk(self, message):
        qualifiers_string = 'asks feels gives has hates hopes is likes ' + \
               'loves needs says shares thinks wants was will wishes wonders :'
        qualifiers = qualifiers_string.split(" ")
        qualifier = None
        for qualifier in qualifiers:
            if message.startswith(qualifier):
                break
        if not qualifier == ":":
            message = message[qualifier.__len__()+1:]
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())

        #login
        opener.open(self.plurk_url + '/Users/login', 
                                   urllib.urlencode({'username': self.username,
                                                     'password': self.password, 
                                                     'api_key': self.api_key}))
        response = opener.open(self.plurk_url + '/Timeline/plurkAdd',
                                   urllib.urlencode({'content': message,
                                                     'qualifier': qualifier,
                                                     'lang': 'en',
                                                     'api_key': self.api_key}))
        return response
